package com.zlyx.easy.web.jpa.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;

import com.zlyx.easy.web.jpa.service.JpaService;

/**
 *
 * @Author 赵光
 * @Desc BaseServiceImpl
 * @Date 2020年5月10日
 */
public class JpaServiceImpl<R extends JpaRepository<T, ID>, T, ID> implements JpaService<R, T, ID> {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	protected R repository;

	@Override
	public T save(T entity) {
		return repository.saveAndFlush(entity);
	}

	@Override
	public List<T> saveAll(List<T> entities) {
		return repository.saveAll(entities);
	}

	@Override
	public void deleteById(ID id) {
		repository.deleteById(id);
	}

	@Override
	public boolean deleteByIds(List<ID> ids) {
		if (ids != null) {
			for (ID id : ids) {
				deleteById(id);
			}
		}
		return true;
	}

	@Override
	public void delete(T entity) {
		repository.delete(entity);
	}

	@Override
	public void deleteAll(List<T> entities) {
		repository.deleteAll(entities);
	}

	@Override
	public T getById(ID id) {
		return repository.findById(id).get();
	}

	@Override
	public T findOne(T t) {
		return repository.findOne(Example.of(t)).get();
	}

	@Override
	public Page<T> findAll(int current, int size) {
		return repository.findAll(PageRequest.of(current, size));
	}

	@Override
	public List<T> findAll(T t) {
		return repository.findAll(Example.of(t));
	}

	@Override
	public Page<T> findAll(T t, int current, int size) {
		return repository.findAll(Example.of(t), PageRequest.of(current, size));
	}

}
